package org.wangduqing.ibatisdao.factory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.log4j.Logger;

public class PackagesToScanUtil {
	
	private static final Logger logger = Logger.getLogger(PackagesToScanUtil.class);
	private static final String SUB_PACKAGE_SCREEN__SUFFIX = ".*";
	private static final String SUB_PACKAGE_SCREEN__SUFFIX_RE = ".\\*";
	
	public static Set<Class<?>> getClasses(String pack){
		
		boolean recursive = false;
		String[] packArr = {};
		
		if(pack.lastIndexOf(SUB_PACKAGE_SCREEN__SUFFIX)!=-1){
			
			packArr = pack.split(SUB_PACKAGE_SCREEN__SUFFIX_RE);
			if(packArr.length>1){
				
				pack = packArr[0];
				for(int i=0; i<packArr.length; i++){
				
					packArr[i] = packArr[i].replace(SUB_PACKAGE_SCREEN__SUFFIX.substring(1), "");
					
				}
				
			}else{
				
				pack = pack.replace(SUB_PACKAGE_SCREEN__SUFFIX, "");
				
			}
			
			recursive = true;
			
		}
		
		Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
		
		String packageName = pack;
		String packageDirName = packageName.replace('.', '/');
		Enumeration<URL> dirs;
		try {
			
			dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
			while(dirs.hasMoreElements()){
				
				URL url = dirs.nextElement();
				String protocol = url.getProtocol();
				// 如果是以文件的形式保存在服务器上
				if("file".endsWith(protocol)){
					
					logger.debug("-------------- file类型的扫描 ----------------");
					String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
					// 以文件的方式扫描整个包下的文件 并添加到集合中
					findAndAddClessesInPackageByFile(packageName, packArr, filePath, recursive, classes);
					
				}else if("jar".equals(protocol)){
					
					findAndAddClassesInPackageByJar(packageName, packArr, url, packageDirName, recursive, classes);
					
				}
				
			}
		} catch (IOException e) {
			
			e.printStackTrace();
			
		}
		
		return classes;
		
	}
	
	public static void findAndAddClessesInPackageByFile(String packageName, String[] packArr, String packagePath, final boolean recursive, Set<Class<?>> classes){
		
		File dir = new File(packagePath);
		if(!dir.exists()||!dir.isDirectory()){
			
			logger.warn("用户定义包名 " + packageName + " 下没有任何文件");
			return;
			
		}
		
		File[] dirFiles = dir.listFiles(new FileFilter(){
			// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
			public boolean accept(File file){
				
				return (recursive&&file.isDirectory())||(file.getName().endsWith(".class"));
				
			}
			
		});
		
		for(File file:dirFiles){
			
			if(file.isDirectory()){
				
				findAndAddClessesInPackageByFile(packageName+"."+file.getName(), packArr, file.getAbsolutePath(), recursive, classes);
				
			}else{
				try {
					// 如果是java类文件 去掉后面的.class 只留下类名
					String className = file.getName().substring(0, file.getName().length()-6);
					String classUrl = packageName + "." + className;
					if(classUrl.endsWith(".")){
						//不能直接用replace因为这样会把里面的所有"."替换了
						classUrl.replaceFirst(".", "");
						
					}
					boolean flag = true;
					if(packArr.length>1){
						
						for(int i=1; i<packArr.length; i++){
							
							if(classUrl.indexOf(packArr[i])<=-1){
								
								flag = flag && false;
								
							}else{
								
								flag = flag && true;
								
							}
							
						}
						
					}
					if(flag){
						
							classes.add(Thread.currentThread().getContextClassLoader().loadClass(classUrl));
						
					}
				} catch (ClassNotFoundException e) {
					
					e.printStackTrace();
					
				}
				
			}
			
		}
		
		
	}
	
	private static void findAndAddClassesInPackageByJar(String packageName, String[] packArr, URL url, String packageDirName, final boolean recursive, Set<Class<?>> classes){
		
		logger.debug("------------------------ jar类型的扫描 ----------------------");
		JarFile jar;
		try {
			jar = ((JarURLConnection)url.openConnection()).getJarFile();
			Enumeration<JarEntry> entries = jar.entries();
			while(entries.hasMoreElements()){
				
				JarEntry entry = entries.nextElement();
				String name = entry.getName();
				if(name.charAt(0)=='/'){
					
					name = name.substring(1);
					
				}
				if(name.startsWith(packageDirName)){
					
					int idx = name.lastIndexOf('/');
					if(idx!=-1){
						
						packageName = name.substring(0, idx).replace('/', '.');
						
					}
					if((idx!=-1)||recursive){
						
						if(name.endsWith(".class")&&!entry.isDirectory()){
							
							String className = name.substring(packageName.length()+1, name.length()-6);
								try {
									
									boolean flag = true;
									if(packArr.length>1){
										
										for(int i=1; i<packArr.length; i++){
											
											if(packageName.indexOf(packArr[i])<=-1){
												
												flag = flag && false;
												
											}else{
												
												flag = flag && true;
												
											}
											
										}
										
									}
									if(flag){
										
										classes.add(Class.forName(packageName+"."+className)); 
										
									}
									
								} catch (ClassNotFoundException e) {
									
									logger.error("添加用户自定义视图类错误 找不到此类的.class文件");
									e.printStackTrace();
									
								}
							
						}
						
					}
					
				}
				
			}
			
		} catch (IOException e) {
			
			logger.error("在扫描用户定义视图时从jar包获取文件出错");
			e.printStackTrace();
			
		}
	}
	

}
